﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Triples {
    public class Deck {

#if DEBUG
        private const int MaxNumberOfCards = 81;
#else
        private const int MaxNumberOfCards = 81;
#endif

        private readonly List<Card> Cards;

        public Deck() : this (null) {
        }


        public Deck(int seed) : this ((int?) seed) {
        }


        private Deck(int? seed) {
            Cards = new List<Card>(MaxNumberOfCards);

            BuildDeck();
            if (seed.HasValue) Shuffle(seed.Value);
            else Shuffle();
        }


        private void BuildDeck() {
            for (byte i = 0; i < MaxNumberOfCards; i++) {
                Cards.Add (new Card(i));
            }
        }


        private void Shuffle () {
            Shuffle(new Random());
        }


        private void Shuffle(int seed) {
            Shuffle(new Random(seed));
        }


        private void Shuffle(Random rand) {
            int length = Cards.Count;

            for (length = Cards.Count - 1; length > 0; length--) {
                int k = rand.Next(length + 1);

                Card value = Cards[k];
                Cards[k] = Cards[length];
                Cards[length] = value;
            }
        }


        public Card Draw () {

            if (CanDraw()) {
                Card drawnCard;
                
                drawnCard = Cards[0];
                Cards.RemoveAt(0);
                return drawnCard;
            }

            else throw new InvalidOperationException();
        }


        public bool CanDraw() {
            return Cards.Count > 0;
        }
    }
}
